import { asyncRouterMap, constantRouterMap } from '@/router'
import { getRouter } from '@/api/login'
/* Layout */
import Layout from '@/views/layout/Layout'
/**
 * 通过meta.role判断是否与当前用户权限匹配
 * @param roles
 * @param route
 */
function hasPermission(roles, route) {
  if (route.meta && route.meta.roles) {
    return roles.some(role => route.meta.roles.indexOf(role) >= 0)
  } else {
    return true
  }
}

/**
 * 递归过滤异步路由表，返回符合用户角色权限的路由表
 * @param asyncRouterMap
 * @param roles
 */
function filterAsyncRouter(asyncRouterMap, roles) {
  const accessedRouters = asyncRouterMap.filter(route => {
    if (route.component === 'Layout') {
      route.component = Layout
    } else if (typeof route.component === 'string' || route.component instanceof String) {
      var str = '@' + route.component
      route.component = () => import(str)
    }
    if (hasPermission(roles, route)) {
      if (route.children && route.children.length) {
        route.children = filterAsyncRouter(route.children, roles)
      }
      return true
    }
    return false
  })
  return accessedRouters
}

const permission = {
  state: {
    routers: constantRouterMap,
    addRouters: []
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRouterMap.concat(routers)
    }
  },
  actions: {
    GenerateRoutes({ commit }, data) {
      return getRouter().then(response => {
        console.log(response)
        return [
          {
            path: '/permission',
            component: 'Layout',
            redirect: '/permission/index',
            alwaysShow: true, // will always show the root menu
            meta: {
              title: 'permission',
              icon: 'lock',
              roles: ['admin', 'editor'] // you can set roles in root nav
            },
            children: [{
              path: 'page',
              component: '/views/permission/page',
              name: 'pagePermission',
              meta: {
                title: 'pagePermission',
                roles: ['admin'] // or you can only set roles in sub nav
              }
            }, {
              path: 'directive',
              component: '/views/permission/directive',
              name: 'directivePermission',
              meta: {
                title: 'directivePermission'
                // if do not set roles, means: this page does not require permission
              }
            }]
          },

          {
            path: '/icon',
            component: 'Layout',
            children: [{
              path: 'index',
              component: '/views/svg-icons/index',
              name: 'icons',
              meta: { title: 'icons', icon: 'icon', noCache: true }
            }]
          },

          {
            path: '/components',
            component: 'Layout',
            redirect: 'noredirect',
            name: 'component-demo',
            meta: {
              title: 'components',
              icon: 'component'
            },
            children: [
              { path: 'tinymce', component: '/views/components-demo/tinymce', name: 'tinymce-demo', meta: { title: 'tinymce' }},
              { path: 'markdown', component: '/views/components-demo/markdown', name: 'markdown-demo', meta: { title: 'markdown' }},
              { path: 'json-editor', component: '/views/components-demo/jsonEditor', name: 'jsonEditor-demo', meta: { title: 'jsonEditor' }},
              { path: 'splitpane', component: '/views/components-demo/splitpane', name: 'splitpane-demo', meta: { title: 'splitPane' }},
              { path: 'avatar-upload', component: '/views/components-demo/avatarUpload', name: 'avatarUpload-demo', meta: { title: 'avatarUpload' }},
              { path: 'dropzone', component: '/views/components-demo/dropzone', name: 'dropzone-demo', meta: { title: 'dropzone' }},
              { path: 'sticky', component: '/views/components-demo/sticky', name: 'sticky-demo', meta: { title: 'sticky' }},
              { path: 'count-to', component: '/views/components-demo/countTo', name: 'countTo-demo', meta: { title: 'countTo' }},
              { path: 'mixin', component: '/views/components-demo/mixin', name: 'componentMixin-demo', meta: { title: 'componentMixin' }},
              { path: 'back-to-top', component: '/views/components-demo/backToTop', name: 'backToTop-demo', meta: { title: 'backToTop' }},
              { path: 'drag-dialog', component: '/views/components-demo/dragDialog', name: 'dragDialog-demo', meta: { title: 'dragDialog' }},
              { path: 'dnd-list', component: '/views/components-demo/dndList', name: 'dndList-demo', meta: { title: 'dndList' }},
              { path: 'drag-kanban', component: '/views/components-demo/dragKanban', name: 'dragKanban-demo', meta: { title: 'dragKanban' }}
            ]
          },

          {
            path: '/charts',
            component: 'Layout',
            redirect: 'noredirect',
            name: 'charts',
            meta: {
              title: 'charts',
              icon: 'chart'
            },
            children: [
              { path: 'keyboard', component: '/views/charts/keyboard', name: 'keyboardChart', meta: { title: 'keyboardChart', noCache: true }},
              { path: 'line', component: '/views/charts/line', name: 'lineChart', meta: { title: 'lineChart', noCache: true }},
              { path: 'mixchart', component: '/views/charts/mixChart', name: 'mixChart', meta: { title: 'mixChart', noCache: true }}
            ]
          },

          {
            path: '/tab',
            component: 'Layout',
            children: [{
              path: 'index',
              component: '/views/tab/index',
              name: 'tab',
              meta: { title: 'tab', icon: 'tab' }
            }]
          },

          {
            path: '/table',
            component: 'Layout',
            redirect: '/table/complex-table',
            name: 'table',
            meta: {
              title: 'Table',
              icon: 'table'
            },
            children: [
              { path: 'dynamic-table', component: '/views/table/dynamicTable/index', name: 'dynamicTable', meta: { title: 'dynamicTable' }},
              { path: 'drag-table', component: '/views/table/dragTable', name: 'dragTable', meta: { title: 'dragTable' }},
              { path: 'inline-edit-table', component: '/views/table/inlineEditTable', name: 'inlineEditTable', meta: { title: 'inlineEditTable' }},
              { path: 'tree-table', component: '/views/table/treeTable/treeTable', name: 'treeTableDemo', meta: { title: 'treeTable' }},
              { path: 'custom-tree-table', component: '/views/table/treeTable/customTreeTable', name: 'customTreeTableDemo', meta: { title: 'customTreeTable' }},
              { path: 'complex-table', component: '/views/table/complexTable', name: 'complexTable', meta: { title: 'complexTable' }}
            ]
          },

          {
            path: '/example',
            component: 'Layout',
            redirect: '/example/list',
            name: 'example',
            meta: {
              title: 'example',
              icon: 'example'
            },
            children: [
              { path: 'create', component: '/views/example/create', name: 'createArticle', meta: { title: 'createArticle', icon: 'edit' }},
              { path: 'edit/:id(\\d+)', component: '/views/example/edit', name: 'editArticle', meta: { title: 'editArticle', noCache: true }, hidden: true },
              { path: 'list', component: '/views/example/list', name: 'articleList', meta: { title: 'articleList', icon: 'list' }}
            ]
          },

          {
            path: '/nested',
            component: 'Layout',
            redirect: '/nested/menu1/menu1-1',
            name: 'nested',
            meta: {
              title: 'nested',
              icon: 'nested'
            },
            children: [
              {
                path: 'menu1',
                component: '/views/nested/menu1/index', // Parent router-view
                name: 'menu1',
                meta: { title: 'menu1' },
                redirect: '/nested/menu1/menu1-1',
                children: [
                  {
                    path: 'menu1-1',
                    component: '/views/nested/menu1/menu1-1',
                    name: 'menu1-1',
                    meta: { title: 'menu1-1' }
                  },
                  {
                    path: 'menu1-2',
                    component: '/views/nested/menu1/menu1-2',
                    name: 'menu1-2',
                    redirect: '/nested/menu1/menu1-2/menu1-2-1',
                    meta: { title: 'menu1-2' },
                    children: [
                      {
                        path: 'menu1-2-1',
                        component: '/views/nested/menu1/menu1-2/menu1-2-1',
                        name: 'menu1-2-1',
                        meta: { title: 'menu1-2-1' }
                      },
                      {
                        path: 'menu1-2-2',
                        component: '/views/nested/menu1/menu1-2/menu1-2-2',
                        name: 'menu1-2-2',
                        meta: { title: 'menu1-2-2' }
                      }
                    ]
                  },
                  {
                    path: 'menu1-3',
                    component: '/views/nested/menu1/menu1-3',
                    name: 'menu1-3',
                    meta: { title: 'menu1-3' }
                  }
                ]
              },
              {
                path: 'menu2',
                name: 'menu2',
                component: '/views/nested/menu2/index',
                meta: { title: 'menu2' }
              }
            ]
          },

          {
            path: '/error',
            component: 'Layout',
            redirect: 'noredirect',
            name: 'errorPages',
            meta: {
              title: 'errorPages',
              icon: '404'
            },
            children: [
              { path: '401', component: '/views/errorPage/401', name: 'page401', meta: { title: 'page401', noCache: true }},
              { path: '404', component: '/views/errorPage/404', name: 'page404', meta: { title: 'page404', noCache: true }}
            ]
          },

          {
            path: '/error-log',
            component: 'Layout',
            redirect: 'noredirect',
            children: [{ path: 'log', component: '/views/errorLog/index', name: 'errorLog', meta: { title: 'errorLog', icon: 'bug' }}]
          },

          {
            path: '/excel',
            component: 'Layout',
            redirect: '/excel/export-excel',
            name: 'excel',
            meta: {
              title: 'excel',
              icon: 'excel'
            },
            children: [
              { path: 'export-excel', component: '/views/excel/exportExcel', name: 'exportExcel', meta: { title: 'exportExcel' }},
              { path: 'export-selected-excel', component: '/views/excel/selectExcel', name: 'selectExcel', meta: { title: 'selectExcel' }},
              { path: 'upload-excel', component: '/views/excel/uploadExcel', name: 'uploadExcel', meta: { title: 'uploadExcel' }}
            ]
          },

          {
            path: '/zip',
            component: 'Layout',
            redirect: '/zip/download',
            alwaysShow: true,
            meta: { title: 'zip', icon: 'zip' },
            children: [{ path: 'download', component: '/views/zip/index', name: 'exportZip', meta: { title: 'exportZip' }}]
          },

          {
            path: '/theme',
            component: 'Layout',
            redirect: 'noredirect',
            children: [{ path: 'index', component: '/views/theme/index', name: 'theme', meta: { title: 'theme', icon: 'theme' }}]
          },

          {
            path: '/clipboard',
            component: 'Layout',
            redirect: 'noredirect',
            children: [{ path: 'index', component: '/views/clipboard/index', name: 'clipboardDemo', meta: { title: 'clipboardDemo', icon: 'clipboard' }}]
          },

          {
            path: '/i18n',
            component: Layout,
            children: [{ path: 'index', component: '/views/i18n-demo/index', name: 'i18n', meta: { title: 'i18n', icon: 'international' }}]
          },

          { path: '*', redirect: '/404', hidden: true }
        ]
      }).then(asyncRouterMap1 => {
        const { roles } = data
        let accessedRouters
        if (asyncRouterMap) {
          accessedRouters = filterAsyncRouter(asyncRouterMap, roles)
        }
        commit('SET_ROUTERS', accessedRouters)
      })
    }
  }
}

export default permission
